<template>
  <div class="active">
    <div
      style="display: flex; align-items: center; justify-content: space-between"
    >
      <h2>供应商价格评审</h2>
      <el-button type="primary" @click="getInfo(true)">刷新</el-button>
    </div>
    <div class="table" ref="tablediv">
      <el-table
        :data="table"
        stripe
        style="width: 100%"
        border
        :span-method="objectSpanMethod"
      >
        <!-- 使用 v-for 循环生成表格列 -->

        <el-table-column prop="key" label="序号" width="80" align="center">
        </el-table-column>

        <el-table-column
          prop="name"
          label="报名供应商"
          width="200"
          align="center"
        >
          <template #default="scope">
            <span class="ellipsis">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作" width="200" align="center">
          <template #default="scope">
            <span class="link" @click="handleView(scope.$index, scope.row)"
              >查看</span
            >
          </template>
        </el-table-column>

        <el-table-column
          label="报价"
          align="center"
          v-if="
            selectedFormula == 'equation_floor_price' ||
            selectedFormula == 'equation_custom'
          "
        >
          <template #default="scope">
            <div class="price-cell">
              <span>￥</span>
              <el-input-number
                @blur="editPrice(scope.row, scope.row.price)"
                v-model="scope.row.price"
                placeholder="输入价格"
                :step="2"
                style="width: 100%"
                :controls="false"
              ></el-input-number>
              <span>元<b v-if="projectInfo.price<scope.row.price" style="color: red;">超出预算,报价无效</b></span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="下浮率"
          align="center"
          v-else-if="selectedFormula == 'equation_float_prob'"
        >
          <template #default="scope">
            <div class="price-cell">
              <el-input-number
                @blur="editPrice(scope.row)"
                v-model="scope.row.price"
                placeholder="输入下浮率"
                :step="2"
                style="width: 100%"
                :controls="false"
              ></el-input-number>
              <span>%</span>
            </div>
          </template>
        </el-table-column>
        <!-- 手动添加操作列 -->
        <el-table-column label="拆算得分" width="120" align="center">
          <template #default="scope">
            <span v-if="selectedFormula != 'equation_custom'">{{
              scope.row.score > 0 ? scope.row.score : 0
            }}</span>
            <el-input
              v-else
              @blur="editPrice(scope.row, scope.row.score)"
              v-model="scope.row.score"
              placeholder="请输入分数"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column
          prop="formula"
          label="公示选择"
          width="140"
          align="center"
        >
          <template #default="scope">
            <div>
              选用公式：<br />
              {{
                selectedFormula == "equation_floor_price"
                  ? "最低价"
                  : selectedFormula == "equation_float_prob"
                  ? "下浮率"
                  : "自定义"
              }}
            </div>
            <span class="link" @click="editformula">选择公式</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="endbutton">
      <el-button type="primary" @click="nextStep">下一步</el-button>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="选公式" align-center width="500">
    <div
      style="
        display: flex;
        justify-content: center;
        width: 70%;
        margin: 0px auto;
      "
    >
      <el-radio-group v-model="selectedFormula" style="display: flex;flex-direction: column;justify-content: center;">
        <el-radio value="equation_floor_price" style="margin: 0;">公式1：最低价</el-radio>
        <el-radio value="equation_float_prob" style="margin: 0;">公式2：下浮率</el-radio>
        <el-radio value="equation_custom" style="margin: 0;">公式3：自定义</el-radio>
      </el-radio-group>
    </div>
    <template #footer>
      <span
        style="
          width: 100%;
          margin-top: 20px;
          display: flex;
          justify-content: space-around;
        "
      >
        <el-button type="primary" @click="confirmSelection" style="width: 30%"
          >确定</el-button
        >
        <el-button
          type="primary"
          @click="dialogVisible = false"
          style="width: 30%"
          >取消</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { judgeProjectInfo } from "@/api/project.js";
import config from "@/utils/config";
import {
  getDictList,
  getDict,
  nowTime,
  getdict,
  SearchDicte,
} from "@/utils/common.js";
import {
  execTask,
  applySupplierInfoByProjectId,
  updateApplySupplier,
  calculatePrice,
  choiceSupplier,
  selectGroupByMark,
  updateScore,
  selectStoreFileList,
} from "@/api/examine.js";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const tablediv = ref({});
const id = computed(() => route.query.id);

const emit = defineEmits(["next-step"]);
const props = defineProps({
  type: {
    type: String,
    required: true,
  },
  projectInfo: {
    type: String,
    required: true,
  },
});
const projectInfo=ref({})
const dialogVisible = ref(false);
const selectedFormula = ref("");
// 定义表格列配置
const taskNode = ref("");
const getInfo = (boolean) => {
  
  judgeProjectInfo({ id: id.value }).then((res) => {
    projectInfo.value.price=res.data.price
  })
  if (boolean) {
    window.location.replace("");
  }
  applySupplierInfoByProjectId({ id: id.value }).then((res) => {
    if (res.code == "200") {
      table.value = [];
      let key = 0;
      for (let i = 0; i < res.data.length; i++) {
        if (res.data[i].status == "apply_supplier_pass") {
          key++;
          table.value[i] = {
            key: key,
            ...res.data[i],
            price: res.data[i].price,
            score: res.data[i].score > 0 ? res.data[i].score : null,
          };
        }
      }
      rowspan.value=key
    }
  });
  judgeProjectInfo({ id: id.value }).then((res) => {
    if (res.code == "200") {
      console.log(res);

      selectedFormula.value = res.data.priceEquation
        ? res.data.priceEquation
        : "equation_floor_price";
      getCalculatePrice();
    }
  });
};
const editformula = () => {
  dialogVisible.value = true;
};
const confirmSelection = () => {
  getCalculatePrice();
  dialogVisible.value = false;
};
const handleView = (item, data) => {
  selectStoreFileList({ applyId: data.id }).then((res) => {
    if (res.code == "200") {
      for (let i = 0; i < res.data.length; i++) {
        if (res.data[i].tableName == "store_apply_price") {
          let url=config.baseUrl+res.data[i].fileUrl
           window.open(url, "_blank"); // 在新窗口中打开
        }
      }
    }
  });
};
const nextStep = async () => {
  if (projectInfo.value.type == "taskPrice") {
    const params = { projectId: id.value };
    execTask(params).then((res) => {
      if (res.code) {
        window.location.replace("");
      }
    });
  } else {
    emit("next-step", 'taskBusiness');
  }
};
interface Supplier {
  id: number;
  supplierCode: string;
  name: string;
  evaluationPoint: string;
  score: number;
}
interface SpanMethodProps {
  row: Supplier;
  column: TableColumnCtx<Supplier>;
  rowIndex: number;
  columnIndex: number;
}
const rowspan = ref(0);
const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}: SpanMethodProps) => {
  const key = column.property;

  if (key === "formula") {
    if (rowIndex % rowspan.value === 0) {
      return {
        rowspan: rowspan.value,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }

  return { rowspan: 1, colspan: 1 };
};
const getCalculatePrice = async () => {
  if (selectedFormula.value == "equation_custom") {
    choiceSupplier({ id: id.value, priceEquation: "equation_custom" }).then(
      (res) => {
        if (res.code == "200") {
          console.log(res);
        }
      }
    );
  } else {
    const params = {
      projectId: id.value,
      type: selectedFormula.value,
    };
    try {
      await calculatePrice(params).then((res) => {
        if (res.code == "200") {
          // getInfo();
        }
      });
    } catch (error) {
      // window.location.replace("");
    }
  }
};
const editPrice = async (row) => {
  console.log(row);
  
  if (Number(row.price)<=0) {
      ElMessage({
        message: "价格无效，请重新输入！",
        type: "error",
      });
    row.price=null
    return

  }
  if (Number(row.score)<=0) {
      ElMessage({
        message: "分数无效，请重新输入！",
        type: "error",
      });
    row.score=null
    return
  }
  if (selectedFormula.value == "equation_custom") {
    let ids = "";
    let list = [];
    await selectGroupByMark({ projectId: id.value, type: "score_price" }).then(
      (res) => {
        list = res.data[0].scoreDtoList;
        for (let i = 0; i < list.length; i++) {
          if (row.supplierId == list[i].scoreList[0].supplierId) {
            ids = list[i].scoreList[0].id;
          }
        }
      }
    );
    updateScore({ id: ids, projectId: id.value, score: row.score });
  } else {
    updateApplySupplier(row).then((res) => {
      if (res.code == "200") {
        getCalculatePrice();
      }
    });
  }
};
// 定义表格数据
const table = ref([]);
onMounted(() => {
  getInfo();
});
</script>

<style scoped lang="scss">
@use "./judge";
</style>
<style scoped>
.price-cell {
  display: flex;
  align-items: center;
}

.price-cell span {
  margin: 0 5px;
}
:deep(.table) {
  display: flex;
}
</style>
